package com.explorati.LeetCode116.connect;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ Author : Weijian_Wang
 * @ Date : Created in 18:32 2020/10/18 0018
 * @ Description ：
 */
public class Solution1 {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    public Node connect(Node root) {
        if(root == null) {
            return root;
        }

        Queue<Node> queue = new LinkedList<Node>();
        queue.add(root);
        while(!queue.isEmpty()) {

            int size = queue.size();
            //当前节点1.next指向下一个节点 2. 子节点放到queue中
            for(int i = 0; i < size ; i ++) {
                Node head = queue.poll();

                if(i < size - 1) {
                    head.next = queue.peek();
                }

                if(head.left != null) {
                    queue.add(head.left);
                }

                if(head.right != null){
                    queue.add(head.right);
                }
            }
        }

        return root;
    }
}
